function alert(txt) {
    $.messager.alert('提示信息', txt)
}


$.extend($.fn.validatebox.defaults.rules, {
    INT: {//
        validator: function (value) {
            return /^[+]?[0-9]+\d*$/i.test(value);
        },
        message: '必须是整数'
    },
    RANGE: {
        validator: function (value, param) {
            if (value > param[0] && value <= param[1]) {
                return true
            } else {
                return false
            }
        },
        message: '输入的数字在{0}到{1}之间'
    },
    FL: {
        validator: function (value) {
            return /^[1-9]\d*(\.\d+)?$/.test(value);
        },
        message: '输入数字格式不正确'
    },
    YZ: {
        validator: function (value) {
            if (!/^[+]?[0-9]+\d*$/i.test(value)) {
                return false;
            }
            value = value - 0;
            var sum = ($("#sp table td").length / $("#sp table tr").length - 1) - 1
            if (value % sum == 0) {
                return true;
            } else {
                return false;
            }
        },
        message: '请输入尺码数量的倍数'
    }
});

//全局参数
var kehu;
var product;
var state=-1;
var stateB=-1;
var stateC=-1;
var stateD=-1;


/**
 * 选择状态
 */
function zhuangtai() {
    $('#dg').datagrid("hideColumn","zhidanrenName")
    $('#dg').datagrid("hideColumn","zhidanshijian")
    $('#dg').datagrid("hideColumn","bohuirenName")
    $('#dg').datagrid("hideColumn","bohuishijian")
    $('#dg').datagrid("hideColumn","shenherenName")
    $('#dg').datagrid("hideColumn","shenheshijian")
    $('#dg').datagrid("hideColumn","tongguorenName")
    $('#dg').datagrid("hideColumn","tongguoshijian")
    $('#dg').datagrid("hideColumn","chukurenName")
    $('#dg').datagrid("hideColumn","chukushijian")
    $('#dg').datagrid("hideColumn","beizhu")
    $('#dg').datagrid("hideColumn","note")
    if ($('#zt1').prop('checked')) {
        state = 0;
        $('#dg').datagrid("showColumn","zhidanrenName")
        $('#dg').datagrid("showColumn","zhidanshijian")
        $('#dg').datagrid("showColumn","bohuirenName")
        $('#dg').datagrid("showColumn","bohuishijian")
        $('#dg').datagrid("showColumn","beizhu")
    } else {
        state = -1;
    }
    if ($('#zt2').prop('checked')) {
        stateB = 1;
        $('#dg').datagrid("showColumn","zhidanrenName")
        $('#dg').datagrid("showColumn","zhidanshijian")
        $('#dg').datagrid("showColumn","bohuirenName")
        $('#dg').datagrid("showColumn","bohuishijian")
        $('#dg').datagrid("showColumn","beizhu")
        $('#dg').datagrid("showColumn","shenherenName")
        $('#dg').datagrid("showColumn","shenheshijian")

    } else {
        stateB = -1;
    }
    if ($('#zt3').prop('checked')) {
        stateC = 2;
        $('#dg').datagrid("showColumn","zhidanrenName")
        $('#dg').datagrid("showColumn","zhidanshijian")
        $('#dg').datagrid("showColumn","bohuirenName")
        $('#dg').datagrid("showColumn","bohuishijian")
        $('#dg').datagrid("showColumn","beizhu")
        $('#dg').datagrid("showColumn","shenherenName")
        $('#dg').datagrid("showColumn","shenheshijian")
        $('#dg').datagrid("showColumn","tongguorenName")
        $('#dg').datagrid("showColumn","tongguoshijian")
        $('#dg').datagrid("showColumn","note")
    } else {
        stateC = -1;
    }
    if ($('#zt4').prop('checked')) {
        stateD = 3;
        $('#dg').datagrid("showColumn","zhidanrenName")
        $('#dg').datagrid("showColumn","zhidanshijian")
        $('#dg').datagrid("showColumn","bohuirenName")
        $('#dg').datagrid("showColumn","bohuishijian")
        $('#dg').datagrid("showColumn","beizhu")
        $('#dg').datagrid("showColumn","shenherenName")
        $('#dg').datagrid("showColumn","shenheshijian")
        $('#dg').datagrid("showColumn","tongguorenName")
        $('#dg').datagrid("showColumn","tongguoshijian")
        $('#dg').datagrid("showColumn","note")
        $('#dg').datagrid("showColumn","chukurenName")
        $('#dg').datagrid("showColumn","chukushijian")
    } else {
        stateD = -1;
    }

}


//获得出库列表
function getChuKuList(){
    zhuangtai()

    var etime = $("#etime").val();
    if (null != etime && '' != etime) {
        etime += " 23:59:59";
    }
    $("#dg").datagrid({
        url: path + '/chuku/chukulist.do',
        queryParams: {
            jgId: $('#bumeng').combotree("getValue"),
            fenlei: 0,//0是出库1是出库退货
            chukuleixing:1,
            state:state,
            stateB:stateB,
            stateC:stateC,
            stateD:stateD,
            qtime:$('#qtime').val(),
            etime:etime,
            wldwName:$('#key').val()

        }
    });
}
//加载子表
function loadChildren(val) {
    var row = $('#dg').datagrid('getSelected');
    $("#subDatagrid").datagrid({
        url: path + '/chuku/chukusonlist.do',
        queryParams: {
            chukuId: row.id,
            type: val
        }
    });
}

$(function () {
    A()
    $('#bumeng').combotree({
        url: path + '/jg/tree.do',
        required: true,
         loadFilter: function (data) {
        return data.rows
    },onLoadSuccess: function (node, data) {
            if (data.length > 0) {
                $("#bumeng").combotree('setValue', data[0].id);
                getChuKuList()
            }
     },onClick:function () {
            getChuKuList()
        }
        })
    loadProduct()

})

/***
 * 刷新款号
 */
function refresh() {
   loadProduct()
}


/***
 *重置搜索条件
 */

function chongzhi() {
    $('#qtime').combo('setValue', '');
    $('#etime').combo('setValue', '');
    $('#etime').combo('clear');
    $('#qtime').combo('clear');
    $("#key").searchbox('setValue', '');
    getChuKuList()
}
/***
 *
 */

function loadProduct(){

    $("#se").combobox({
        url: path + '/production/allysxpro.do',
        valueField: 'id',
        textField: 'product',
        onSelect: function (record) {

            product = record


        }, loadFilter: function (data) {
            return data.data
        }, onHidePanel: function () {
            $('#sp').empty();
            record=product
            var table = "<table><thead><tr><td></td>";
            for (var i = 0; i < record.sizeArray.length; i++) {
                table += "<td align='center'><span class='cm'>" + record.sizeArray[i] + "</span></td>"
            }
            table += "<td align='center'>小计</td></tr></tr></thead><tbody>"


            for (var i = 0; i < record.colorArray.length; i++) {
                table += "<tr><td>" + record.colorArray[i] + "</td>"
                table += "<td><input name='shuliang' onkeyup='diaoyong(this)'  class='easyui-validatebox cs'  validType='INT'  style='width:50px;border-radius:5px'></td>"
                for (var j = 0; j < record.sizeArray.length - 1; j++) {
                    table += "<td><input name='shuliang' class='easyui-validatebox cs'  validType='INT' style='width:50px; border-radius:5px'></td>"

                }
                table += "<td><input name='shuliang' onkeyup='diaoyong1(this)'  class='easyui-validatebox '  validType='YZ' style='width:50px;border-radius:5px'></td>"
                table += "</tr>"
            }

            table += "</tbody></table><span>快捷键操作:填充数据(Enter);保存编辑(Shift+Enter)</span>";
            $('#sp').append(table)
            $('#cc').combo('showPanel');
            $.parser.parse($("#sp"));//格式样式
            $("#sp .cs").keyup(function () {
                var sum = 0;
                for (var j = 1; j < $("#sp table td").length / $("#sp table tr").length - 1; j++) {
                    if (/^[+]?[0-9]+\d*$/.test(parseInt($("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq(j).children().val()))) {
                        sum += parseInt($("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq(j).children().val())
                    }
                }
                $("#sp table").find("tr").eq($(this).parents('table tr').index()).find("td").eq($("#sp table td").length / $("#sp table tr").length - 1).children().val(sum)
            });
            flg=false
            $("#sp table").find("tr").eq(1).find("td").eq(1).children().focus();

        }
    })

}

/***
 * 开启编辑框
 */
function winOpen() {
    //加载分销商
    $('#fenxiaoshang').combobox({
        url: path + '/jg/selectjgforleixing.do',
        valueField: 'id',
        textField: 'kehuming',
        onLoadSuccess: function () {  // 加载完成后,设置选中第一项
            var val = $(this).combobox("getData");
            for (var item in val[0]) {
                if (item == "id") {
                    $(this).combobox("select", val[0][item]);
                }
            }

        },
        onSelect: function (record) {
            $("#SHDZ").val(record.address)
            $('#phone').val(record.phone)
            if (record.fenxiao_zhekou == null) {
                record.fenxiao_zhekou = 1
            }
            kehu = record
        },
        loadFilter: function (data) {
            console.log(data)
            return data.data

        }
    });

/*    $('#fenxiaoshang').combotree({
        url: path + '/jg/tree/all.do',
        required: true,
        loadFilter: function (data) {

            if($('#jgleixing').val()!=0 && $('#jgleixing').val()!=1) {

                for (var i = 0; i < data.rows[0].children.length; i++) {

                    if ($("#jgid").val() != data.rows[0].children[i].id && data.rows[0].children[i].id != $('#parentId').val()) {
                        data.rows[0].children[i].state = "closed"
                    }
                }
            }
            return data.rows
        },onLoadSuccess: function (node, data) {

            $("#fenxiaoshang").combotree('setValue', data[0].id);
        },onClick:function (node) {
            if(node.fenxiao_zhekou==null ){
                node.fenxiao_zhekou=1
            }
            $("#SHDZ").val(node.address)
            $('#phone').val(node.phone)
             kehu=node
        },
        formatter:function(node){

                 return node.text
        },onBeforeExpand:function(node){
          if($('#jgleixing').val()!=0 && $('#jgleixing').val()!=1){
                if($('#jgid').val()!=node.id && node.id!=1 && data.rows[0].children[i].id != $('#parentId').val()){
                    alert("不是本机构不可展开")
                    return false
                }else{
                    return true
                }

                if(node.id!=$('#parentId').val()){
                    alert("不是本机构不可展开")
                    return false
                }else{
                     return true
              }

            }else {
                return true
            }

        },
        onBeforeSelect:function(node){

            if($('#jgid').val()!=node.id){
                             if($('#jgleixing').val()!=0 && $('#jgleixing').val()!=1){

                                 if(node.parent_id==$('parentId').val() || node.parent_id== $('#jgid').val()){


                                 }else{
                                     alert("不能选择该客户!")
                                     $('#fenxiaoshang').combotree("unselect");
                                 }

                                 if($('#jgleixing').val()!=0 && $('#jgleixing').val()!=1 && $('#jgleixing').val()!=2 ){
                                     if($('#parentId').val()!=node.parent_id &&node.leixing!=0 &&node.leixing!=1){
                                         alert("不能选择其他省代")
                                         $('#fenxiaoshang').combotree("unselect");
                                     }
                                 }
                             }
             }else{
                alert("不能选择其他省代")
                $('#fenxiaoshang').combotree("unselect");
            }




        }
    })*/
    $('#chukuId').val("")
    $('#h2').text("销 售 单")
    $('#w').window('open')

}

function winClose() {
    $('#bjdg').datagrid('loadData', {
        total: 0,
        rows: []
    });// 重置dataGRID
    $('#zk1').attr('checked','checked');
    $("#zongjia").text(0.00);
    $("#zongjianshu").text(0)
    $("#zongkuanshu").text(0)
    $("#SHDZ").val('')
    $('#phone').val('')
    $('#chukuId').val("")
    $('#w').window('close')

}

$(function () {

    $('#bjdg').datagrid(
        {
            iconCls: 'icon-edit',
            singleSelect: false,
            title: '编辑商品',
            fitColumns: true,
            onDblClickRow: onClickRow,

            columns: [[
                {
                    field: 'id',
                    title: 'productID',
                    checkbox: true,
                    align: 'center'
                }, {
                    field: 'product',
                    title: '款号',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'productName',
                    title: '款名',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'color',
                    title: '颜色',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'size',
                    title: '尺码',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'pinpai',
                    title: '品牌',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'year',
                    title: '年份',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'season',
                    title: '季节',
                    width: 90,
                    align: 'center'
                }, {
                    field: 'price',
                    title: '铭牌价',
                    width: 90,
                    align: 'right'
                }, {
                    field: 'zhekou',
                    title: '折扣',
                    width: 90,
                    align: 'right',
                    editor: {
                        type: 'validatebox',
                        options: {
                            required: true,
                            validType: 'RANGE[0,1]'

                        }
                    }
                }, {
                    field: 'sjdanjia',
                    title: '实际单价',
                    width: 90,
                    align: 'right',
                    editor: {
                        type: 'validatebox',
                        options: {
                            required: true,
                            validType: 'FL'

                        }
                    }
                }, {
                    field: 'shuliang',
                    title: '数量',
                    width: 90,
                    align: 'right',
                    editor: {
                        type: 'validatebox',
                        options: {
                            required: true,
                            validType: 'INT'
                        }
                    }
                }, {
                    field: 'sjzongjia',
                    title: '实际总价',
                    width: 90,
                    align: 'right'
                }

            ]]

        })


    /*出库上面表格*/
    $("#dg").datagrid({
        method: 'GET',
        striped: true,
        rownumbers: false,
        singleSelect: true,
        toolbar: '#tb',
        checkbox: false,
        fit: true,
        striped: true,
        fitColumns: false,
        autoRowHeight: false,
        rownumbers: true,
        pagination: true,
        pageSize: 15,
        pageList: [15, 30, 50],
        nowrap: true,
        loadMsg: '加载中,请稍后......',
        columns: [[{
            field: 'id',
            title: '出库单Id',
            width: 80,
            hidden: true
        },{
            field: 'jgName',
            title: '所属机构',
            width: 130,
            align: 'center'
        }, {
            field: 'chukudanhao',
            title: '出库单号',
            width: 130,
            align: 'center'
        }, {
            field: 'state',
            title: '状态',
            width: 90,
            align: 'center',
            styler: function (value, row, index) {

                if (row.state == 0) {

                    return 'color:red;'
                } else if (row.state == 1) {
                    return 'color:yellow'
                } else if (row.state == 2) {
                    return 'color:orange'
                } else {
                    return 'color:green'
                }
            },
            formatter: function (value, row, index) {
                if (value == 0) {
                    if(row.bohuishijian!=null){
                        return '草稿(驳回)'
                    }else{
                        return '草稿'
                    }
                } else if (value == 1) {
                    return '待审核'
                } else if (value == 2) {
                    return '已审核'
                } else if (value == 3) {
                    return '已出库'
                }
            }
        }, {
            field: 'chukuleixing',
            title: '出库类型',
            width: 80,
            align: 'center',
            formatter: function (value, row, index) {
                if (value == 0) {
                    return "批发";
                } else {
                    return "分销";
                }
            }
        }, {
            field: 'wldwName',
            title: '客户名称',
            width: 130,
            align: 'center'
        }, {
            field: 'phone',
            title: '联系方式(客户)',
            width: 90,
            align: 'center'
        }, {
            field: 'zshuliang',
            title: '总件数',
            width: 90,
            align: 'right',
            formatter: function (value, row, index) {
                if(value<0){
                     value=value*-1
                }
                return value
            }
        }, {
            field: 'zongjia',
            title: '总金额',
            width: 90,
            align: 'right',
            formatter: function (value, row, index) {
                if(value<0){
                    value=value*-1
                }
                return value.toFixed(2)
            }
        }, {
            field: 'yearandseason',
            title: '年季',
            width: 80,
            align: 'center'
        },{
            field: 'address',
            title: '发货地址',
            width: 120,
            align: 'center'
        }, {
            field: 'zhidanshijian',
            title: '制单时间',
            width: 150,
            align: 'center'
        }, {
            field: 'zhidanrenName',
            title: '制单人',
            width: 80,
            align: 'center'
        }, {
            field: 'shenheshijian',
            title: '提交时间',
            width: 150,
            align: 'center'
        }, {
            field: 'shenherenName',
            title: '提交人',
            width: 80,
            align: 'center'
        },{
            field: 'tongguoshijian',
            title: '审核时间',
            width: 150,
            align: 'center'
        }, {
            field: 'tongguorenName',
            title: '审核人',
            width: 80,
            align: 'center'
        }
        , {
            field: 'chukushijian',
            title: '出库时间',
            width: 150,
            align: 'center'
        }, {
            field: 'chukurenName',
            title: '出库人',
            width: 90,
            align: 'center'
        }, {
            field: 'bohuishijian',
            title: '驳回时间',
            width: 150,
            align: 'center'
        }, {
            field: 'bohuirenName',
            title: '驳回人',
            width: 80,
            align: 'center'
        }, {
            field: 'beizhu',
            title: '驳回备注',
            width: 120,
            align: 'center'
        }, {
            field: 'note',
            title: '审核备注',
            width: 120,
            align: 'center'
        }, {
                field: 'picSrc',
                title: '回执单',
                width: 190,
                align: 'center',
                formatter: function (value, row, index) {
                              if(value!=null && value!=''){

                                    return  "<a onClick=as('"+value+"') style='color: #0000ee'>查看</a>"
                              }else{
                                    return "<a onClick='huiPic()' style='color: #0000ee'>暂无</a>"
                              }

            }
        }
        ]],
        onSelect: function (index, row) {
            loadChildren($(".fenlei:checked").val())
        },
        onBeforeLoad: function (param) {
        },
        onLoadSuccess: function (data) {

            $('#dg').datagrid("selectRow", 0);
            $('#key').next('span').find('input').focus()
        }
    });

    $('#subDatagrid').datagrid({
        striped: true,
        rownumbers: false,
        singleSelect: true,
        toolbar: '#tb3',
        checkbox: false,
        fit: true,
        striped: true,
        fitColumns: false,
        autoRowHeight: false,
        rownumbers: true,
        nowrap: true,
        loadMsg: '加载中,请稍后......',
        columns: [[{
            field: 'productrRetailId',
            title: '商品编号',
            width: 80,
            hidden: true
        },{
            field: 'productId',
            title: '商品款号',
            width: 80,
            hidden: true
        },{
            field: 'product',
            title: '商品款号',
            width: 80,  align: 'center'

        },{
            field: 'productName',
            title: '商品名称',
            width: 80,align: 'center'

        },{
            field: 'price',
            title: '铭牌价',
            width: 80,align: 'right'
        },{
            field: 'color',
            title: '颜色',
            width: 80,align: 'center'

        },{
            field: 'size',
            title: '尺码',
            width: 80,align: 'center'
        },{
            field: 'zongshu',
            title: '数量',
            width: 80,align: 'right'
        },{
            field: 'danjia',
            title: '单价',
            width: 80,align: 'right',
            formatter:function(value, row, index){
                if(value!=null){
                    return value.toFixed(2)
                }
                return value

            }
        },{
            field: 'zongjia',
            title: '总价',
            width: 80,align: 'right',
            formatter:function(value, row, index){
                if(value!=null){
                    return value.toFixed(2)
                }
                return value

            }
        }

        ]],
        loadFilter: function (data) {
            return data.data
        }, onLoadSuccess:function(){
            if($(".fenlei:checked").val()==0){
                $('#subDatagrid').datagrid("hideColumn","color")
                $('#subDatagrid').datagrid("hideColumn","size")
            }else if($(".fenlei:checked").val()==1){
                $('#subDatagrid').datagrid("showColumn",'color')
                $('#subDatagrid').datagrid("hideColumn",'size')

            }else if($(".fenlei:checked").val()==2){
                $('#subDatagrid').datagrid("showColumn",'color')
                $('#subDatagrid').datagrid("showColumn",'size')

            }

        }
    })



})


var editIndex = undefined;
function endEditing() {
    if (editIndex == undefined) {
        return true
    }
    if ($('#bjdg').datagrid('validateRow', editIndex)) {
        $('#bjdg').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

function onClickRow(index) {
    if (editIndex != index) {
        if (endEditing()) {
            $('#bjdg').datagrid('clearSelections');
            $('#bjdg').datagrid('selectRow', index)
                .datagrid('beginEdit', index);
            setEditing(index);
            editIndex = index;
        } else {
            $('#bjdg').datagrid('selectRow', editIndex);
        }

    }
    sum()
}


//保存编辑
function accept() {
    if (endEditing()) {
        if (shu()) {
        for (var i = 1; i < $("#sp table tr").length; i++) {
            for (var j = 1; j < $("#sp table td").length / $("#sp table tr").length - 1; j++) {
                if ($("#sp table").find("tr").eq(i).find("td").eq(j).children().val() == '' || $("#sp table").find("tr").eq(i).find("td").eq(j).children().val() == 0) {
                    continue
                }
                $('#bjdg').datagrid('appendRow', {
                    id: product.id,
                    product: product.product,
                    productName: product.productName,
                    color: $("#sp table").find("tr").eq(i).find("td").eq(0).text(),
                    size: $("#sp table").find("tr").eq(0).find("td").eq(j).children('.cm').text(),
                    pinpai: product.pinpai,
                    year: product.year,
                    season: product.season,
                    price: product.price,
                    zhekou: kehu.fenxiao_zhekou,
                    sjdanjia: (kehu.fenxiao_zhekou * product.price).toFixed(2),
                    shuliang: $("#sp table").find("tr").eq(i).find("td").eq(j).children().val(),
                    sjzongjia: (kehu.fenxiao_zhekou * product.price * $("#sp table").find("tr").eq(i).find("td").eq(j).children().val()).toFixed(2)

                });
            }
        }
        sum()
        $('#sp').empty();
        $('#se').combobox("clear")
        $('#cc').combo('hidePanel');
        $('#se').combobox().next('span').find('input').focus()// 聚焦到combobox
        flag = false
    }

    }
}

//求总数量和总价
function sum() {
    var rows = $("#bjdg").datagrid("getRows");
    var zongjia = 0;
    var zongjianshu = 0;
    var productId = []
    for (var i = 0; i < rows.length; i++) {
        zongjianshu += parseInt(rows[i].shuliang);
        zongjia += parseFloat(rows[i].sjzongjia)
        productId.push(rows[i].id)
    }
    $("#zongjia").text(zongjia.toFixed(2));
    $("#zongjianshu").text(zongjianshu)
    $("#zongkuanshu").text(uniq(productId).length)

}




//
function setEditing(rowIndex) {
    var editors = $('#bjdg').datagrid('getEditors', rowIndex);

    var zhekou = editors[0];
    var danjia = editors[1];
    var shuliang = editors[2];

    zhekou.target.bind('change', function () {
        calculate1();
    });
    danjia.target.bind('change', function () {
        calculate2();
    });
    shuliang.target.bind('change', function () {
        calculate3();
    });

    //改zhekou
    function calculate1() {
        var rows = $('#bjdg').datagrid('getRows')
        if ($('#zk1').prop('checked')) {
            if ($('#bjdg').datagrid('validateRow', editIndex)) {
                $(danjia.target).val(parseFloat($('#bjdg').datagrid('getRows')[editIndex]['price'] * zhekou.target.val()).toFixed(2));
                $('#bjdg').datagrid('getRows')[editIndex]['sjzongjia'] = parseFloat(danjia.target.val() * shuliang.target.val()).toFixed(2)

                for (var i = 0; i < rows.length; i++) {
                    rows[i]['zhekou'] = zhekou.target.val()
                    rows[i]['sjdanjia'] = (zhekou.target.val() * rows[i]['price']).toFixed(2)
                    rows[i]['sjzongjia'] = (rows[i]['sjdanjia'] * rows[i]['shuliang']).toFixed(2)
                    $('#bjdg').datagrid('refreshRow', i)
                }
            }

        } else if ($('#zk2').prop('checked')) {
            if ($('#bjdg').datagrid('validateRow', editIndex)) {
                $(danjia.target).val(parseFloat($('#bjdg').datagrid('getRows')[editIndex]['price'] * zhekou.target.val()).toFixed(2));
                $('#bjdg').datagrid('getRows')[editIndex]['sjzongjia'] = parseFloat(danjia.target.val() * shuliang.target.val()).toFixed(2)

                for (var i = 0; i < rows.length; i++) {
                    if (rows[i]['id'] == $('#bjdg').datagrid('getRows')[editIndex]['id']) {
                        rows[i]['zhekou'] = zhekou.target.val()
                        rows[i]['sjdanjia'] = (zhekou.target.val() * rows[i]['price']).toFixed(2)
                        rows[i]['sjzongjia'] = (rows[i]['sjdanjia'] * rows[i]['shuliang']).toFixed(2)
                        $('#bjdg').datagrid('refreshRow', i)
                    }
                }
            }
        }

        endEditing()
        sum()
    }

    //改单价
    function calculate2() {
        var rows = $('#bjdg').datagrid('getRows')
        if ($('#bjdg').datagrid('validateRow', editIndex)) {
            $(zhekou.target).val(parseFloat(danjia.target.val() / $('#bjdg').datagrid('getRows')[editIndex]['price']).toFixed(2));
            $('#bjdg').datagrid('getRows')[editIndex]['sjzongjia'] = parseFloat(danjia.target.val() * shuliang.target.val()).toFixed(2)
        }
        for (var i = 0; i < rows.length; i++) {
            if (rows[i]['id'] == $('#bjdg').datagrid('getRows')[editIndex]['id']) {
                rows[i]['sjdanjia'] = danjia.target.val()
                rows[i]['zhekou'] = (danjia.target.val() / rows[i]['price']).toFixed(2)
                rows[i]['sjzongjia'] = (rows[i]['sjdanjia'] * rows[i]['shuliang']).toFixed(2)
                $('#bjdg').datagrid('refreshRow', i)
            }
        }
        endEditing()
        sum()
    }
    //改数量
    function calculate3() {

        if ($('#bjdg').datagrid('validateRow', editIndex)) {
            $('#bjdg').datagrid('getRows')[editIndex]['sjzongjia'] = parseFloat(danjia.target.val() * shuliang.target.val()).toFixed(2)
        }
        endEditing()
        sum()
    }
}

// 验证输入数量
function shu(){
    for(var i=1;i<$("#sp table tr").length;i++){

        for(var j=1;j<$("#sp table td").length/$("#sp table tr").length-1;j++){
            if($("#sp table").find("tr").eq(i).find("td").eq(j).children().val()!=''&&$("#sp table").find("tr").eq(i).find("td").eq(j).children().val()!=0){
                if(!/^[+]?[1-9]+\d*$/.test($("#sp table").find("tr").eq(i).find("td").eq(j).children().val())){

                    $('#cc').combo('showPanel')

                    $("#sp table").find("tr").eq(i).find("td").eq(j).children().focus()
                    return false;

                }
                /*  if($("#sp table").find("tr").eq(i).find("td").eq(j).children().attr('placeholder')!='')
                 if($('#indx').val()==2){
                 if(parseInt($("#sp table").find("tr").eq(i).find("td").eq(j).children().attr('placeholder'))<$("#sp table").find("tr").eq(i).find("td").eq(j).children().val()){
                 $('#cc').combo('showPanel')
                 $("#sp table").find("tr").eq(i).find("td").eq(j).children().focus()
                 return false;
                 }
                 }else{
                 return true
                 }*/
            }
        }
    }

    if($("#sp table td").length==0){

        return false
    }
    if($('#bjdg').datagrid('getRows').length!=0){
        for(var i=0;i<$('#bjdg').datagrid('getRows').length;i++){

            if($('#se').combobox('getText')==$('#bjdg').datagrid('getData').rows[i].product )// 亚麻色
            {
                for (var j = 1; j < $("#sp table tr").length; j++) {

                    if($("#sp table").find("tr").eq(j).find("td").eq(0).text()!=''){

                        for (var z = 1; z < $("#sp table td").length/$("#sp table tr").length-1; z++) {

                            if($("#sp table").find("tr").eq(j).find("td").eq(z).children().val()!=''){
                                if($("#sp table").find("tr").eq(j).find("td").eq(0).text()==$('#bjdg').datagrid('getData').rows[i].color){

                                    if($("#sp table").find("tr").eq(0).find("td").eq(z).children('.cm').text()==$('#bjdg').datagrid('getData').rows[i].size){
                                        $('#cc').combo('hidePanel');
                                        doSearch($('#se').combobox('getText'))
                                        alert($('#se').combobox('getText')+":"+$("#sp table").find("tr").eq(j).find("td").eq(0).text()+":"+$("#sp table").find("tr").eq(0).find("td").eq(z).children('.cm').text()+'已添加')
                                        return 	false;

                                    }

                                }


                            }

                        }


                    }
                }
            }
        }
    }
    return true;
}



// 添加出库
function addChuKu(){

    var chukuson="["

    var rows = $("#bjdg").datagrid("getRows");

    if(rows==''){
        $.messager.alert('提示!', '无编辑数据!', 'warning');
        return
    }
      for(var i=0;i<rows.length;i++){

          chukuson += "{'productoinId':'" + rows[i].id+"','color':'" + rows[i].color+"','size':'" + rows[i].size+"','shuliang':'" +rows[i].shuliang+"','danjia':'"+rows[i].sjdanjia+ "'},"

      }
    chukuson=chukuson.substring(0,chukuson.length-1)+"]"
    if($("#yearandseason").combobox("getText")==''){
        $.messager.alert('提示!', '年季不能为空!', 'warning');
        return

    }
 /*   if(sum!=parseInt($("#zongjianshu").text() || zongjia!=parseFloat($("#zongjia").text()))){
        $.messager.alert('提示!', '数据异常请刷新页面重试!', 'warning');
        return
    }*/
   if ($("#fenxiaoshang").combobox('getValue')==0 ||$("#fenxiaoshang").combobox('getValue')=='' || ($("#fenxiaoshang").combobox('getText')==$("#fenxiaoshang").combobox('getValue'))) {
        $.messager.alert('提示!', '请选择往来单位!', 'warning');
        return;
    }

    $('#save1').linkbutton('disable');
    $('#noqiuxiao').linkbutton('disable');
    $.ajax({
        url: path+'/chuku/save.do',
        type:'post',
        data:{
            id:$('#chukuId').val(),
            wanglaidanwei:$("#fenxiaoshang").combotree('getValue'),
            phone:$('#phone').val(),
            address:$('#SHDZ').val(),
            chukusonString:chukuson,
            chukuleixing:1,
            fenlei:0,
            yearandseason:$('#yearandseason').combobox("getText")

        },
        dataType:'json',
        success:function (data) {

               if(data.code==200){
                   winClose()
                   getChuKuList()
                   $.messager.show({
                       title: '提示',
                       msg: data.msg,
                       timeout: 4000,
                       showType: 'slide'
                   })
               }else{
                 alert(data.msg)
               }
        },complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
            if (status == 'timeout') {// 超时,status还有success,error等值的情况
                ajaxTimeoutTest.abort();
                $.messager.show({
                    title:'提示',
                    msg:'请求超时！',
                    timeout:1000,
                    showType:'slide'
                });
                $('#save1').linkbutton('enable');
                $('#noqiuxiao').linkbutton('enable');
            }
            $('#save1').linkbutton('enable');
            $('#noqiuxiao').linkbutton('enable');
        }

    })
    $('#chukuId').val('')
}


// 编辑删除
function removeit() {
    var selRow = $('#bjdg').datagrid('getSelections')
    if(selRow==0){
        alert('请选择要删除的行！');
        return

    }else{
        $.messager.confirm('提示信息', '真的要执行删除操作', function(r){
            if (r){
                for(var i=0;i<selRow.length;i++){
                    var index = $('#bjdg').datagrid(
                        'getRowIndex', selRow[i]);
                    $('#bjdg').datagrid('cancelEdit', editIndex)
                        .datagrid('deleteRow', index);
                    sum();
                    editIndex = undefined;
                }
            }
        })
    }
}




//出库单提交
function commit(){

    if($('#bumeng').combotree('getValue')!=$("#jgid").val()){
        alert("不可以操作非本机构数据！");
        return;
    }
    if($('#dg').datagrid("getSelected")!=null){
    $.messager.confirm('提示信息', '请确认提交：'+$('#dg').datagrid("getSelected").chukudanhao, function(r){
        if (r){
            if(r==""){
                r=" "
            }
            $('#tj').linkbutton('disable');
            $.ajax({
                url:path+'/chuku/updatechuku.do',
                type:'post',
                data:{
                    chukuId:$('#dg').datagrid("getSelected").id,
                    state:1,
                    beizhu:''
                },
                dataType:'json',
                success:function(data){
                       if(data.code==200){

                           $.messager.show({
                               title:'提示',
                               msg:'提交成功！',
                               timeout:400,
                               showType:'slide'
                           });
                           getChuKuList()
                       }else{
                         alert(data.msg)
                           $('#tj').linkbutton('enable');
                       }
                },complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
                    if (status == 'timeout') {// 超时,status还有success,error等值的情况
                        ajaxTimeoutTest.abort();
                        $.messager.show({
                            title:'提示',
                            msg:'请求超时！',
                            timeout:1000,
                            showType:'slide'
                        });
                        $('#tj').linkbutton('enable');

                    }
                    $('#tj').linkbutton('enable');

                }
            })
        }
    });
    }else{
        alert("请选择操作行!")
    }

}

//审核通过还是驳回

function shenhe(state){

   if($('#bumeng').combotree('getValue')!=$("#jgid").val()){
        alert("不可以操作非本机构数据！");
        return;
    }
    if($('#dg').datagrid("getSelected")!=null){

        $.messager.prompt('提示信息', '下框添加备注，可为空', function(r){
            if(r==""){
                r=" "
            }
            if (r){
                if(state==0){
                    $('#bh').linkbutton('disable');
                }else if(state==2){
                    $('#tg').linkbutton('disable');
                }
                $.ajax({
                    url:path+'/chuku/updatechuku.do',
                    type:'post',
                    data:{
                        chukuId:$('#dg').datagrid("getSelected").id,
                        state:state,
                        beizhu:r
                    },
                    dataType:'json',
                    success:function(data){
                        if(data.code==200){
                            getChuKuList()
                            $.messager.show({
                                title:'提示',
                                msg:'提交成功！',
                                timeout:400,
                                showType:'slide'
                            });
                        }else{
                               alert(data.msg)
                            if(state==0){
                                $('#bh').linkbutton('enable');
                            }else if(state==2){
                                $('#tg').linkbutton('enable');
                            }
                        }
                    },complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
                        if (status == 'timeout') {// 超时,status还有success,error等值的情况
                            ajaxTimeoutTest.abort();
                            $.messager.show({
                                title:'提示',
                                msg:'请求超时！',
                                timeout:1000,
                                showType:'slide'
                            });

                            if(state==0){
                                $('#bh').linkbutton('enable');
                            }else if(state==2){
                                $('#tg').linkbutton('enable');
                            }
                        }
                        if(state==0){
                            $('#bh').linkbutton('enable');
                        }else if(state==2){
                            $('#tg').linkbutton('enable');
                        }

                    }
                })
            }
        });
    }else{
        alert("请选择操作行!")
    }

}


//删除单

function del(){
    if($('#bumeng').combotree('getValue')!=$("#jgid").val()){
        alert("不可以操作非本机构数据！");
        return;
    }
    if($('#dg').datagrid("getSelected")!=null){
        $.messager.confirm('提示信息', '请确认删除：'+$('#dg').datagrid("getSelected").chukudanhao, function(r){
            if (r){
                $('#sc').linkbutton('disable');
                $.ajax({
                    url:path+'/chuku/delchuku.do',
                    type:'post',
                    data:{
                        chukuId:$('#dg').datagrid("getSelected").id
                    },
                    dataType:'json',
                    success:function (data) {

                        if(data.code==200){

                            getChuKuList()
                            $.messager.show({
                                title:'提示',
                                msg:data.msg,
                                timeout:400,
                                showType:'slide'
                            });
                            $('#sc').linkbutton('enable');
                        }else{

                            alert(data.msg)

                        }
                    },complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
                        if (status == 'timeout') {// 超时,status还有success,error等值的情况
                            ajaxTimeoutTest.abort();
                            $.messager.show({
                                title:'提示',
                                msg:data.msg,
                                timeout:1000,
                                showType:'slide'
                            });
                            $('#sc').linkbutton('enable');
                        }
                        $('#sc').linkbutton('enable');

                    }

                })

            }})
    }

}

function xiugai(){
    if($('#bumeng').combotree('getValue')!=$("#jgid").val()){
        alert("不可以操作非本机构数据！");
        return;
    }
    $('#fenxiaoshang').combobox({
        url: path + '/jg/selectjgforleixing.do',
        valueField: 'id',
        textField: 'kehuming',
        onSelect: function (record) {
            $("#SHDZ").val(record.address)
            $('#phone').val(record.phone)
            if (record.fenxiao_zhekou == null) {
                record.fenxiao_zhekou = 1
            }
            kehu = record
        },
        loadFilter: function (data) {
            console.log(data)
            return data.data

        }
    });

    $.ajax({
        url:path+'/chuku/xiuchuku.do',
        type:"post",
        data:{
            chukuId:$('#dg').datagrid("getSelected").id
        },
        dataType:'json',
        success:function(data){
            if(data.code==200){
                $('#fenxiaoshang').combobox("select", data.data[0].wanglaidanwei)
                $("#bjdg").datagrid("loadData",data.data[0].chukuson)
                $('#yearandseason').combobox("setValue",data.data[0].yearandseason)
                $("#SHDZ").val(data.data[0].address)
                $('#phone').val(data.data[0].phone)
                $('#chukuId').val($('#dg').datagrid("getSelected").id)
                sum()
                $('#h2').text("销 售 单 (修改)")
                $('#w').window('open')
            }else{
             alert(data.msg)
            }
        }
    })

}


function chuku(){

    if($('#bumeng').combotree('getValue')!=$("#jgid").val()){
        alert("不可以操作非本机构数据！");
        return;
    }

    if($('#dg').datagrid("getSelected")!=null){

        $.messager.confirm('提示信息', '请确认出库：'+$('#dg').datagrid("getSelected").chukudanhao, function(r){
            if (r){
                $('#rukuspan').linkbutton('disable');
                $.ajax({
                    url:path+'/chuku/chukux.do',
                    type:"post",
                    data:{
                        chukuId:$('#dg').datagrid("getSelected").id
                    },
                    dataType:'json',
                    success:function(data){
                        if(data.code==200){
                            getChuKuList()
                            $.messager.show({
                                title:'提示',
                                msg:data.msg,
                                timeout:1000,
                                showType:'slide'
                            });
                            $('#rukuspan').linkbutton('enable');
                        }else{
                            $('#rukuspan').linkbutton('enable');
                            alert(data.msg)
                        }
                    },complete: function (XMLHttpRequest, status) { // 请求完成后最终执行参数
                        if (status == 'timeout') {// 超时,status还有success,error等值的情况
                            ajaxTimeoutTest.abort();
                            $.messager.show({
                                title:'提示',
                                msg:'请求超时！',
                                timeout:1000,
                                showType:'slide'
                            });
                        }
                        $('#rukuspan').linkbutton('enable')

                    }
                })
            }
        })

    }




}










//生成
function A() {
   var year= ""+new Date().getFullYear();
   var yearandseason= [{
       "id":1,
       "text":(parseInt(year)+1)+"春夏"
   },{
       "id":2,
       "text":(parseInt(year)+1)+"秋"
   },{
       "id":3,
       "text":(parseInt(year)+1)+"冬",

   },{
        "id":4,
        "text":year+"春夏"
    },{
        "id":5,
        "text":year+"秋"
    },{
        "id":6,
        "text":year+"冬",

    }]
   $("#yearandseason").combobox("loadData",yearandseason)

}

//数组去重
function uniq(array) {
    var temp = [];
    var index = [];
    var l = array.length;
    for (var i = 0; i < l; i++) {
        for (var j = i + 1; j < l; j++) {
            if (array[i] === array[j]) {
                i++;
                j = i;
            }
        }
        temp.push(array[i]);
        index.push(i);
    }

    return temp;
}

//打印
function print(){
    if ($('#bumeng').combotree('getValue') != $("#jgid").val()) {
        alert("不可以操作非本机构数据！");
        return;
    }

    if ($('#dg').datagrid("getSelected") != null) {
        $('#print').linkbutton('disable');
        var url= path + '/print.do?chukuId='+$('#dg').datagrid("getSelected").id
        window.open(url)
        $('#print').linkbutton('enable');
    }else{
        alert("请选择操作行!")
    }

}
